﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace blackhouse.WebNemo.Data {
    public class SystemNames {

        #region Fields

        private IDataAccess data;
        private Dictionary<int, string> names;

        #endregion

        #region Properties

        private Dictionary<int, string> Names {
            get {
                if (this.names == null) {
                    Dictionary<int, string> d = new Dictionary<int, string>();
                    KeyValuePair<int, string>[] di = this.data.GetGroupSystemNames();
                    foreach (KeyValuePair<int, string> dii in di)
                        d.Add(dii.Key, dii.Value.ToUpper());
                    this.names = d;
                }
                return this.names;
            }
        }

        #endregion

        #region Constructors

        public SystemNames(IDataAccess data) {
            this.data = data;
        }

        #endregion

        #region Methods

        public string GetSelectName(int groupId) {
            if (this.Names.ContainsKey(groupId))
                return this.Names[groupId];
            else return string.Empty;
        }

        public int GetGroupId(string groupName) {
            groupName = groupName.ToUpper();
            if (this.Names.ContainsValue(groupName))
                return this.Names.First(k => k.Value == groupName).Key;
            else return 0;
        }

        /// <summary>
        /// Pobiera nazwę tabeli dla relacji FN.
        /// </summary>
        /// <param name="parentGroupId">Jest to ID grupy relacyjnej z której chcemy pobierać rekordy</param>
        /// <param name="relatedGroupId">Jest to ID grupy w której znajduje się kolumna FN</param>
        /// <returns></returns>
        public string GetSelectNameForRelation(int parentGroupId, string columnName, int relatedGroupId) {
            string select = String.Empty;
            if (string.IsNullOrEmpty(columnName)) {
                GroupColumnData gcd = this.data.GetColumns(relatedGroupId).FirstOrDefault(c => c.RelatedGroupId == parentGroupId);
                if (gcd.RelatedGroupId == parentGroupId)
                    select = GetSelectName(relatedGroupId) + '_' + gcd.ColumnName;
            }
            select = GetSelectName(relatedGroupId);
            if (!String.IsNullOrEmpty(select))
                select = select + '_' + columnName.ToLower();
            return select;
        }

        #endregion

    }
}
